package com.growthgate.bootcommon.config;

import com.fasterxml.classmate.TypeResolver;
import com.growthgate.bootcommon.common.ResponseResult;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMethod;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.ResponseMessageBuilder;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ResponseMessage;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Swagger2配置
 *
 * @author GrowthGate
 * @date 2020/2/18
 */
@Configuration
@EnableSwagger2
public class Swagger2Config {

    @Resource
    private TypeResolver typeResolver;

    @Bean
    public Docket createRestApi() {
        List<ResponseMessage> responseMessages = new ArrayList<>();
        responseMessages.add(new ResponseMessageBuilder().code(500).message("服务器异常").responseModel(new ModelRef("ResponseResult«null»")).build());

        return new Docket(DocumentationType.SWAGGER_2)
                .pathMapping("/")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.growthgate.bootcommon.controller"))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(new ApiInfoBuilder()
                        .title("BootCommon")
                        .description("SpringBoot通用练习项目")
                        .build())
                // 返回信息列表
                .globalResponseMessage(RequestMethod.GET, responseMessages)
                .globalResponseMessage(RequestMethod.POST, responseMessages)
                .globalResponseMessage(RequestMethod.PUT, responseMessages)
                .globalResponseMessage(RequestMethod.DELETE, responseMessages)
                .additionalModels(typeResolver.resolve(ResponseResult.class, void.class))
                // 将Date转化为Long
                .directModelSubstitute(Date.class, Long.class);
    }

}